const { Model, DataTypes } = require('sequelize')
const { createFields } = require('../helper')

module.exports = (sequelize) => {
  class User extends Model {
    static associate({ Role }) {
      User.belongsToMany(Role, {
        as: 'roleList',
        through: 'sys_user_role',
        constraints: false,
      })
    }
  }

  User.init(
    createFields({
      username: { type: DataTypes.STRING(50), allowNull: false },
      password: { type: DataTypes.STRING(255), allowNull: false },
      isSuperAdmin: { type: DataTypes.BOOLEAN, defaultValue: false },
      salt: { type: DataTypes.STRING(255), allowNull: false },
      email: { type: DataTypes.STRING(100), allowNull: true },
      phone: { type: DataTypes.STRING(20), allowNull: true },
      status: { type: DataTypes.TINYINT(10), defaultValue: 1 },
      lastLoginAt: { type: DataTypes.DATE, allowNull: true },
      lastLoginIp: { type: DataTypes.STRING(20), allowNull: true },
    }),
    {
      sequelize,
      tableName: 'sys_user',
      timestamps: true,
      modelName: 'User',
    }
  )
  return User
}
